<template>
  <span>{{ displayText }}</span>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useDictStore } from "@/stores/dict";

const props = defineProps({
  // 字典类型
  dictType: {
    type: String,
    required: true,
  },
  // 当前字典值
  value: {
    type: [String, Number],
    default: "",
  },
});

const dictStore = useDictStore();
// 字典选项
const dictOptions = ref([]);
// 加载状态
const loading = ref(false);

// 计算显示文本
const displayText = computed(() => {
  if (!props.value) return "";
  
  const option = dictOptions.value.find(item => item.value == props.value);
  return option ? option.label : props.value;
});

// 加载字典数据
const loadDictData = async () => {
  if (!props.dictType) return;

  loading.value = true;
  try {
    const response = await dictStore.fetchDictDataByType({ code: props.dictType });
    
    if (response) {
      dictOptions.value = response.map((item) => ({
        value: item.value,
        label: item.label,
      }));
    } else {
      dictOptions.value = [];
    }
  } catch (error) {
    // 加载字典数据失败处理
    dictOptions.value = [];
  } finally {
    loading.value = false;
  }
};

// 重新加载数据
const reload = () => {
  dictStore.reloadDictData({ code: props.dictType });
};

// 暴露方法给父组件
const getOptions = () => dictOptions.value;

defineExpose({
  reload,
  getOptions,
});

// 组件挂载时加载数据
onMounted(() => {
  loadDictData();
});
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>